package com.css.fxfzfxqh.zcpt.sys.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzfxqh.zcpt.sys.entity.SysUserRole;
import com.css.fxfzfxqh.zcpt.sys.service.SysRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class SysRoleCacheService {
    @Autowired
    SysRoleService sysRoleService;
    @Autowired
    private RedisTemplate redisTemplate;
    public final static String SYS_USER_ROLES = "fxqh:sys:user_roles:";
    /**
     * 查询用户权限信息
     *
     * @param userId
     * @return
     */
    public List<SysUserRole> getRole(String userId) {
        try {
            ValueOperations<String, List<SysUserRole>> ops = redisTemplate.opsForValue();
            List<SysUserRole> sysUserRoles = ops.get(SYS_USER_ROLES + userId);
            if (CollectionUtils.isEmpty(sysUserRoles)) {
                String roleStr = sysRoleService.getRoleByUserId(userId);
                if (StringUtils.isNotBlank(roleStr)) {
                    sysUserRoles = JSONObject.parseArray(roleStr, SysUserRole.class);
                }
                if (sysUserRoles == null) {
                    return null;
                }
                ops.set(SYS_USER_ROLES + userId, sysUserRoles);
                redisTemplate.expire(SYS_USER_ROLES + userId, 60, TimeUnit.MINUTES);
            }
            return sysUserRoles;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
